import {Component, OnInit} from '@angular/core';
// 表格导出为Excel
import * as XLSX from 'xlsx';

import {ApplicationService} from '../../../service/application.service';
import {FarmPlantPowerService} from '../../../service/farm-plant-power.service';

import {FarmService} from '../../../service/farm.service';
import {Farm} from '../../../entity/farm.model';
import {FarmPlantpower} from '../../../entity/farm-plant-power.model';
import {LossElectricityService} from '../../../service/loss-electricity.service';
import {DatePipe} from '@angular/common';
import {ConfirmationService} from 'primeng/primeng';

@Component({
  selector: 'app-farm-plantpower',
  templateUrl: './farm-plantpower.component.html',
  styleUrls: ['./farm-plantpower.component.css']
})
export class FarmPlantpowerComponent implements OnInit {
  date = new Date();
  years: string[] = ['2017', '2018', '2019', '2020', '2021', '2022', '2023', '2024', '2025'];
  months: string[] = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];
  isCheckedYear: boolean = false;
  currentDate: string = '';
  displayDialog: boolean;
  cols: any[];
  farmPlantpower: FarmPlantpower = new FarmPlantpower(0, 0, '');

  selectedfarmPlantpower: FarmPlantpower;

  newFarmPlantpower: boolean;

  farmPlantpowers: FarmPlantpower[] = [];
  original: FarmPlantpower[] = [];

  farms: Farm[] = [];
  myFarms: Farm[] = [];

  selectFarmId: number = 21;
  index: number = -1;
  datePlant: string = '2017-01-01'
  // currentYear: string = "2017";
  currentYear: string = this.date.getFullYear().toString();
  currentMonth: string = this.months[this.date.getMonth()].toString();
  //公司计划发电量
  companyPlantPower: number = 0;
  //公司校准电量
  companyAdjustPower: number = 0;
  file: File;
  fileOther: File;
  filePlant: File;

  constructor(
    private farmPlantpowerService: FarmPlantPowerService,
    private datePipe: DatePipe,
    public application: ApplicationService,
    public farmServer: FarmService,
    private confirmation: ConfirmationService,
    private lossElectricity: LossElectricityService
  ) {

  }

  ngOnInit() {
    this.cols = [
      {field: 'farmName', header: '风场'},
      {field: 'datePlant', header: '时间'},
      {field: 'plantPower', header: '计划发电量(kWh)'},
      {field: 'adjustPower', header: '校准电量(kWh)'}
    ];
    this.initData();
    this.farms = this.application.currentUserFarms;
    //当前用户的有权限的的风场
    //2018/10/9 杨继明  18519500983要求添加公司
    // let company:Farm = new Farm(0,this.farms[0].companyId,'','公司','','',0,'',0,0,'','','','','','','');
    // this.farms.unshift(company)
    // console.log(this.farms.push(company))
    //所有风场
    // this.farmServer.getFarms()
    // .then(res =>{
    //   this.farms = [...res]
    // })
    // .catch(err =>{
    //   console.log(err)
    // })

  }

  initData() {
    this.farmPlantpowerService.getFarmPlantPowerList()
      .then(res => {
        if (res) {
          this.original = [...res];
        }
        this.onSearch(this.currentYear, this.currentMonth);
      })
      .catch(err => {
      })
  }

  //点击月度
  onSearchMonth() {
    this.displayDialog = false;
    this.isCheckedYear = false;
    this.onSearch(this.currentYear, this.currentMonth);
  }

  //点击年度
  onSearchYear() {
    this.displayDialog = false;
    this.isCheckedYear = true;
    this.onSearch(this.currentYear, this.currentMonth);
  }

  //查询
  onSearch(currentYear, currentMonth) {
    this.displayDialog = false;
    if (this.isCheckedYear) {
      this.currentDate = `${currentYear}`
      this.currentYear = currentYear;
      if (this.original != undefined) {
        this.original.forEach(item => {
          if (item.plantType == 'year') {
            item.datePlant = item.datePlant.slice(0, 4)
          }
        })
        this.farmPlantpowers = this.original.filter(item => item.datePlant == this.currentDate && item.plantType == 'year');
        let farmPlantpowerYear = [];
        this.farms.forEach(farm => {
          this.farmPlantpowers.forEach(farmPlantpower => {
            if (farm.farmId == farmPlantpower.farmId) {
              farmPlantpower.farmName = farm.farmName;
              farmPlantpowerYear.push(farmPlantpower)
            }
          })
        })
        this.farmPlantpowers = farmPlantpowerYear
        //归0
        //公司计划发电量
        this.companyPlantPower = 0;
        //公司校准电量
        this.companyAdjustPower = 0;
        //累加

        this.farmPlantpowers.forEach(o => {
          //公司计划发电量
          this.companyPlantPower += o.plantPower;
          //公司校准电量
          this.companyAdjustPower += o.adjustPower;
        })
      }
    } else {
      this.currentDate = `${currentYear}-${currentMonth}`
      this.currentMonth = currentMonth;
      this.currentYear = currentYear;
      if (this.original != undefined) {

        this.original.forEach(item => {
          if (item.plantType == 'month') {
            item.datePlant = item.datePlant.slice(0, 7);
          }
        });
        this.farmPlantpowers = this.original.filter(item => item.datePlant == this.currentDate && item.plantType == 'month');
        let farmPlantpowerMonth = [];
        this.farms.forEach(farm => {
          this.farmPlantpowers.forEach(farmPlantpower => {
            if (farm.farmId == farmPlantpower.farmId) {
              farmPlantpower.farmName = farm.farmName;
              farmPlantpowerMonth.push(farmPlantpower)
            }
          })
        })
        this.farmPlantpowers = farmPlantpowerMonth
        //归0
        //公司计划发电量
        this.companyPlantPower = 0;
        //公司校准电量
        this.companyAdjustPower = 0;
        //累加
        this.farmPlantpowers.forEach(o => {
          //公司计划发电量
          this.companyPlantPower += o.plantPower;
          //公司校准电量
          this.companyAdjustPower += o.adjustPower;
        })
      }
    }
    this.farmPlantpowers.push({
      'farmId': 0,
      'plantPowerId': 0,
      'farmName': '公司',
      'plantType': '公司',
      'datePlant': this.farmPlantpowers[0].datePlant,
      'plantPower': this.companyPlantPower,
      'adjustPower': this.companyAdjustPower,
      'powertype': '',
    });
  }

  //点击增加按钮
  showDialogToAdd() {
    this.newFarmPlantpower = true;
    this.farmPlantpower = new FarmPlantpower(0, 0, '');
    this.displayDialog = true;
    this.index = -1;
    this.datePlant = '2017-01-01';
    if (this.isCheckedYear) {
      this.farmPlantpower.datePlant = this.currentYear
    } else {
      this.farmPlantpower.datePlant = this.currentYear + '-' + this.currentMonth
    }
    // this.filterFarms()
  }

  // 保存
  save() {
    this.farms.forEach(farm => {
      if (farm.farmId == this.selectFarmId) {
        this.farmPlantpower.farmId = this.selectFarmId;
        this.farmPlantpower.farmName = farm.farmName;
      }
    })

    let searchFarmPlantpowers = [...this.farmPlantpowers];
    this.datePlant = this.farmPlantpower.datePlant;

    if (this.isCheckedYear) {
      //点击年度
      this.farmPlantpower.plantType = 'year';
      if (this.farmPlantpower.datePlant != null) {
        this.farmPlantpower.datePlant = this.farmPlantpower.datePlant.slice(0, 4) + '-01-01'
      }
    } else {
      //点击月度
      if (this.farmPlantpower.datePlant != null) {
        this.farmPlantpower.datePlant = this.farmPlantpower.datePlant.slice(0, 4) + '-' + this.farmPlantpower.datePlant.slice(5, 7) + '-01'
      }
      this.farmPlantpower.plantType = 'month';
    }

    this.index = this.farmPlantpowers.findIndex(o => o.farmId == this.farmPlantpower.farmId)

    if (this.newFarmPlantpower) {
      if (this.index == -1 && this.farmPlantpower.datePlant != null) {

        this.getBasicPlantPowerByTypes(this.farmPlantpower.farmId, this.farmPlantpower.plantType, this.farmPlantpower.datePlant)
          .then(res => {
            if (!res) {
              this.farmPlantpower.plantPower = Number(this.farmPlantpower.plantPower);
              this.farmPlantpower.adjustPower = this.farmPlantpower.adjustPower ? Number(this.farmPlantpower.adjustPower) : 0;
              let currentFarmPlantpower = {...this.farmPlantpower}
              this.farmPlantpowerService.create(this.farmPlantpower)
                .then(res => {
                  currentFarmPlantpower.plantPowerId = res.plantPowerId
                  this.original.push({...currentFarmPlantpower});
                  this.onSearch(this.currentYear, this.currentMonth);
                })
              searchFarmPlantpowers.push({...this.farmPlantpower});
              this.farmPlantpowers = searchFarmPlantpowers;
              this.farmPlantpower = null;
              this.displayDialog = false;
            }
          })

      }

    }
    else {
      if (this.farmPlantpower.datePlant != null) {
        //后台更新
        this.farmPlantpowerService.update(this.farmPlantpower);

        // 前台更新
        // if (this.farmPlantpower.plantType == 'year') {
        //   this.farmPlantpower.datePlant = this.farmPlantpower.datePlant.slice(0, 4);
        // } else {
        //   this.farmPlantpower.datePlant = this.farmPlantpower.datePlant.slice(0, 7);
        // }

        // searchFarmPlantpowers[this.findselectedfarmPlantpowerIndex()] = this.farmPlantpower;

        // this.original[this.findselectedfarmPlantpowerIndexByOriginal()] = this.farmPlantpower;

        // this.farmPlantpowers = searchFarmPlantpowers;
        this.farmPlantpower = null;
        this.displayDialog = false;
        this.initData();
      }
    }

  }

  getBasicPlantPowerByTypes(farmId, plantType, datePlant): any {
    return this.farmPlantpowerService.hasFarmPlantpower(farmId, plantType, datePlant);
  }

  // 查找选中的计划电量
  findselectedfarmPlantpowerIndex(): number {
    return this.farmPlantpowers.indexOf(this.selectedfarmPlantpower);
  }

  findselectedfarmPlantpowerIndexByOriginal(): number {
    return this.original.indexOf(this.selectedfarmPlantpower);
  }

  // 删除
  delete() {
    let index = this.findselectedfarmPlantpowerIndex();
    let deletePlantpowers = this.farmPlantpowers.filter((val, i) => i == index);

    let indexOriginal = this.findselectedfarmPlantpowerIndexByOriginal();
    let deleteOriginalPlantpowers = this.original.filter((val, i) => i == indexOriginal);


    if (deletePlantpowers.length > 0) {
      //后台删除
      this.farmPlantpowerService.delete(deleteOriginalPlantpowers[0].plantPowerId)
        .then(res => {
          if (res.code == 200) {
            //前台删除
            this.farmPlantpowers = this.farmPlantpowers.filter((val, i) => i != index);
            this.original = this.original.filter((val, i) => i != indexOriginal);

            this.farmPlantpower = null;
            this.displayDialog = false;
          }
          if (res.code == -1) {
            console.log('删除失败')
          }
        })
    }


  }

  onUploadPlant(ev) {
    this.filePlant = ev.files;
    this.farmPlantpowerService.importPlannedPower(this.filePlant).then(res => {
      if (res && res.code == '200') {
        alert('导入成功');
        this.initData();
        this.onRemovePlant();
      } else {
        alert('导入失败');
      }
    });
  }

  onRemovePlant() {
    this.filePlant = null;
  }

  // 导入数据
  /* onImport() {
    this.lossElectricity.importBattery(this.file)
      .then(res => {
        this.initData();
        this.onRemoveOther();
      });
  }

  onUpload(ev) {
    this.file = ev.files;
    this.onImport();

  }
  onRemove() {
    this.file = null;
  }
  onUploadOther(ev) {
    this.fileOther = ev.files;
    this.lossElectricity.importOtherBattery(this.fileOther)
      .then(res => {
        this.initData();
        this.onRemoveOther();
      });

  }
  onRemoveOther() {
    this.fileOther = null;
  } */

  //选中某一行
  onRowSelect(event) {
    this.newFarmPlantpower = false;
    this.farmPlantpower = this.cloneFarmPlantpower(event.data);
    this.selectFarmId = this.farmPlantpower.farmId;
    this.displayDialog = true;
    this.index = -1;
    this.datePlant = '2017-01-01';
    // this.filterFarms()
  }


  //过滤风场集合
  // filterFarms() {
  //   console.log(this.farmPlantpowers)
  //   this.myFarms = Array.from(this.farms);
  //   this.myFarms.forEach((farm, index) => {
  //     this.farmPlantpowers.forEach(farmPlantpower => {
  //       if (farm.farmId == farmPlantpower.farmId) {
  //         this.myFarms.splice(index, 1);
  //       }
  //     })
  //   })
  //   console.log(this.myFarms)
  // }

  //选中日期
  // onClickYear(year) {
  //   this.currentYear = year;
  //   this.displayDialog = false;
  // }
  // onClickMonth(month) {
  //   this.currentMonth = month
  //   this.displayDialog = false;
  // }

  //克隆选中行的数据
  cloneFarmPlantpower(c: FarmPlantpower): FarmPlantpower {
    let farmPlantpower = new FarmPlantpower(0, 0, '');
    for (let prop in c) {
      farmPlantpower[prop] = c[prop];
    }
    return farmPlantpower;
  }

  onChangeYear(ev) {
    this.currentYear = ev;
    this.displayDialog = false;
  }

  onChangeMonth(ev) {
    this.currentMonth = ev;
    this.displayDialog = false;
  }

  export() {
    const fomat = 'yyyy.MM',
      fomatYear = 'yyyy';
    let str = ` 
    <thead>
      <tr>
        <th>计划电量</th>
      </tr>
      <tr>
        <th>风场</th>
        <th>时间类型</th>
        <th>时间</th>
        <th>值(kwh)</th>
      </tr>
    </thead>
    <tbody>`;
    this.farmPlantpowers.forEach(farmPlantpower => {
      let plantType = '月';
      let date = '';
      if (farmPlantpower.plantType == 'month') {
        date = this.datePipe.transform(farmPlantpower.datePlant, fomat)
        plantType = '月';
      } else if (farmPlantpower.plantType == 'year') {
        date = this.datePipe.transform(farmPlantpower.datePlant, fomatYear)
        plantType = '年';
      }
      str += `<tr >
        <td>${farmPlantpower.farmName}</td>
        <td>${plantType}</td>
        <td>${date}</td>
        <td>${farmPlantpower.plantPower}</td>
      </tr>`;
    })
    str += `</tbody>
  `;
    /*  var html = '<html><head><meta charset="utf-8" /></head><body >' + str + '</body></html>';

     // 实例化一个Blob对象，其构造函数的第一个参数是包含文件内容的数组，第二个参数是包含文件类型属性的对象
     var blob = new Blob([html], { type: 'application/vnd.ms-excel' });
     // var a = document.getElementsByTagName('a')[0];
     // 利用URL.createObjectURL()方法为a元素生成blob URL
     var href = URL.createObjectURL(blob);
     document.getElementById('ex').setAttribute('href', href);
     // // 设置文件名，目前只有Chrome和FireFox支持此属性
     document.getElementById('ex').setAttribute('download', '计划电量.xls');
     // a.download = '实际功率曲线.xls';
     // a.click();
     document.getElementById('ex').click(); */
    // const ws: XLSX.WorkSheet = XLSX.utils.aoa_to_sheet(this.data);

    /* generate workbook and add the worksheet */
    const elemTable = document.createElement('table');
    elemTable.innerHTML = str;
    const wb: XLSX.WorkBook = XLSX.utils.book_new();
    let ws = XLSX.utils.table_to_sheet(elemTable);
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
    /* save to file */
    XLSX.writeFile(wb, '计划电量.xlsx');
  }

  exportData() {
    this.confirmation.confirm({
      header: '提示信息',
      message: '是否导出计划电量?',
      accept: () => {
        this.export();
      },
      reject: () => {
      }
    });
  }
}
